<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\exception\PDOException;
use app\admin\library\Auth;

/**
 * 导航管理
 *
 * @icon   fa fa-bar-chart
 * @remark
 */
class Article extends Backend
{

    /**
     * @var \app\common\model\Article
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Article');

        //文章分类
        $tree = Tree::instance();
        $tree->init(collection(model('ArticleCategory')->order('sort desc,id asc')->select())->toArray(), 'pid');
        $this->articlecategorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $articlecategorydata=array();
        $articlecategorydata[0]='请选择分类';
        if(!empty($this->articlecategorylist)){
            foreach ($this->articlecategorylist as $k => $v) {
                $articlecategorydata[$v['id']] = $v['name'];
            }
        }
        $this->parentlist=$articlecategorydata;
        $this->view->assign("articleCategoryData", $articlecategorydata);

        //文章标签
        $articleTags=collection(model('tags')->field('id,name')->order('sort desc,id desc')->select())->toArray();
        $this->view->assign('articleTags',$articleTags);

    }

    public function index(){

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $yesNoArr=['否','是'];
            foreach ($list as $k => &$v) {
                $v['category_id']=$v['category_id']?db('ArticleCategory')->where('id='.$v['category_id'])->value("concat(id,'-',name) as info"):'';
                $v['isding']=$v['isding'].'-'.$yesNoArr[$v['isding']];
                $v['isindex']=$v['isindex'].'-'.$yesNoArr[$v['isindex']];
                $v['isrecommend']=$v['isrecommend'].'-'.$yesNoArr[$v['isrecommend']];
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        return parent::edit($ids);
    }

    /**
     * 导入
     */
    public function import_file()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }

        if (pathinfo($file)['extension'] == 'txt') {
            $this->import_txt($file);
        } else {
            $this->import_excel($file);
        }
    }

    protected function import_txt($file)
    {
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }

        // 读取文章内容
        $fileContent = file_get_contents($filePath);
        // 先分割标题、简介、关键词、描述、详情
        $articleArr = [];
        $infoArr = explode('简介：', $fileContent);
        if (empty($infoArr[0]) || empty($infoArr[1])) $this->error('缺少标题或简介');
        $titleArr = explode('标题：', $infoArr[0]);
        if (empty($titleArr[1])) $this->error('缺少标题');
        $articleArr['title'] = trim($titleArr[1]);

        $keywordsArr = explode('关键词：', $infoArr[1]);
        if (empty($keywordsArr[0]) || empty($keywordsArr[1])) $this->error('缺少简介或关键词');
        $articleArr['info'] = trim($keywordsArr[0]);

        $describeArr = explode('描述：', $keywordsArr[1]);
        if (empty($describeArr[0]) || empty($describeArr[1])) $this->error('缺少关键词或描述');
        $articleArr['keywords'] = trim($describeArr[0]);

        $contentArr = explode('详情：', $describeArr[1]);
        if (empty($contentArr[0]) || empty($contentArr[1])) $this->error('缺少描述或详情');
        $articleArr['describe'] = trim($contentArr[0]);
        $articleArr['content'] = $contentArr[1];

        // 查询上一篇文章内容
        $lastArticle = db('article')->order('id', 'desc')->limit(1)->find();
        $articleArr['author'] = $lastArticle['author'];
        $articleArr['isding'] = $lastArticle['isding'];
        $articleArr['avatar'] = $lastArticle['avatar'];
        $articleArr['isindex'] = $lastArticle['isindex'];
        $articleArr['isrecommend'] = $lastArticle['isrecommend'];
        $articleArr['category_id'] = $lastArticle['category_id'];
        $articleArr['createtime'] = time();
        $articleArr['updatetime'] = time();
        db('article')->insert($articleArr);

        $this->success();
    }

    /**
     * excel导入
     */
    protected function import_excel($file)
    {
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                // 查询上一篇文章内容
                $lastArticle = db('article')->order('id', 'desc')->limit(1)->find();
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }

                    $row['author'] = $lastArticle['author'];
                    $row['isding'] = $lastArticle['isding'];
                    $row['avatar'] = $lastArticle['avatar'];
                    $row['isindex'] = $lastArticle['isindex'];
                    $row['isrecommend'] = $lastArticle['isrecommend'];
                    $row['category_id'] = $lastArticle['category_id'];
                    $row['createtime'] = time();
                    $row['updatetime'] = time();
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
